package com.example.demo.controller;

import cn.hutool.core.util.IdUtil;
import com.example.demo.entity.*;
import com.example.demo.entity.dto.ModifyRemarksInput;
import com.example.demo.entity.dto.OrderInput;
import org.babyfish.jimmer.client.FetchBy;
import org.babyfish.jimmer.sql.JSqlClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
public class OrderController {

    @Autowired
    private JSqlClient sqlClient;


    private static final BizOrderFetcher bizOrderFetcher = BizOrderFetcher.$.allScalarFields().items(
            BizOrderItemFetcher.$.allScalarFields()
        );

    @PostMapping("createOrder")
    public void createOrder(HttpServletRequest request, @RequestBody OrderInput orderInput) {
        BizOrder entity = orderInput.toEntity();
        entity = Objects.createBizOrder(entity, e -> {
            String userId = request.getHeader("userId");
            e.setUserId(Long.valueOf(userId));
            e.setOrderNo(IdUtil.getSnowflakeNextIdStr());
        });

        sqlClient.save(entity);
    }

    @GetMapping("orderList")
    public List<@FetchBy("bizOrderFetcher") BizOrder> orderList() {
        List<BizOrder> all = sqlClient.getEntities().findAll(bizOrderFetcher);
        return all;
    }

    @PostMapping("modifyRemarks")
    public void modifyRemarks(@RequestBody ModifyRemarksInput modifyRemarksInput) {
        sqlClient.save(modifyRemarksInput);
    }
}
